//
//  Infor_Search_ViewController.m
//  Pacific_Computer
//
//  Created by 范琦 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "Infor_Search_ViewController.h"
#import "AJComboBox.h"
#import "UIColor+AddColor.h"
#import "Infor_Search.h"
#import "NetHandler.h"
#import "InforSearchCell.h"
#import "Infor_details_ViewController.h"
#import "Infor_SearchProduct.h"
#import "ShowCell.h"
#import "InforProductCell.h"
#import "Product_Details_ViewController.h"

@interface Infor_Search_ViewController ()<AJComboBoxDelegate,UITextFieldDelegate,UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain) AJComboBox *combox;
@property(nonatomic, retain) NSArray *arr;
@property(nonatomic, retain) NSString *str;
@property(nonatomic, retain) UITextField *text;
@property(nonatomic, retain) UITableView *table1;
@property(nonatomic, retain) UITableView *table2;
@property(nonatomic, retain) NSArray *allArr;
@property(nonatomic, retain) NSMutableArray *productArr;

@end

@implementation Infor_Search_ViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"搜索";
    self.arr = [[NSArray alloc]initWithObjects:@"资讯", @"产品", nil];
    self.productArr = [NSMutableArray array];
    
    NSUserDefaults *uf = [NSUserDefaults standardUserDefaults];
    self.allArr = [uf arrayForKey:@"user1"];
    if (self.allArr.count == 0) {
        self.allArr = [NSArray array];
    }
    
    self.combox = [[AJComboBox alloc]initWithFrame:CGRectMake(5, 10, self.view.bounds.size.width / 4 - 10, 30)];
    [self.combox setLabelText:@"资讯"];
    [self.combox setDelegate:self];
    self.combox.arrayData = self.arr;
    [self.view addSubview:self.combox];
    
    self.text = [[UITextField alloc]initWithFrame:CGRectMake(self.combox.frame.origin.x + self.combox.bounds.size.width + 10, self.combox.frame.origin.y, self.view.bounds.size.width / 2 + 20, 30)];
    [self.view addSubview:self.text];
    self.text.clearButtonMode = UITextFieldViewModeAlways;
    self.text.borderStyle = UITextBorderStyleRoundedRect;
    self.text.font = [UIFont systemFontOfSize:14];
    self.text.delegate = self;
    [_text release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.view addSubview:button];
    [button setTitle:@"搜索" forState:UIControlStateNormal];
    button.frame = CGRectMake(self.text.frame.origin.x + self.text.bounds.size.width, self.text.frame.origin.y, self.view.bounds.size.width / 4 - 20, 30);
    [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    self.table1 = [[UITableView alloc]initWithFrame:CGRectMake(self.text.frame.origin.x, self.text.frame.origin.y + 30, self.text.bounds.size.width, 0) style:UITableViewStylePlain];
    [self.view addSubview:self.table1];
    self.table1.backgroundColor = [UIColor redColor];
    self.table1.rowHeight = 30;
    self.table1.delegate = self;
    self.table1.dataSource = self;
    
    self.table2 = [[UITableView alloc]initWithFrame:CGRectMake(5, self.text.frame.origin.y + 100,self.view.bounds.size.width - 10, 0) style:UITableViewStylePlain];
    [self.view addSubview:self.table2];
    self.table2.backgroundColor = [UIColor whiteColor];
    self.table2.rowHeight = 100;
    self.table2.delegate = self;
    self.table2.dataSource = self;
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    [button1 setTitle:@"清除记录" forState:UIControlStateNormal];
    button1.frame = CGRectMake(0, 0, 60, 50);
    button1.titleLabel.font = [UIFont systemFontOfSize:13];
    [button1 addTarget:self action:@selector(clear:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
    
    
}

- (void)click:(UIButton *)button
{

    self.allArr = [self.allArr arrayByAddingObject:self.text.text];
    NSUserDefaults *uf = [NSUserDefaults standardUserDefaults];
    [uf setObject:self.allArr forKey:@"user1"];
    if (self.combox.selectedIndex == 0) {
        [self.productArr removeAllObjects];
        self.str = [NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v2/cms/search?q=%@&clusterQuery=cluster_channel:新闻文章", self.text.text];
        [NetHandler getDataWithUrl:self.str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *aa = [result objectForKey:@"articleList"];
            for (NSDictionary *dic in aa) {
                Infor_Search *search = [[Infor_Search alloc]init];
                [search setValuesForKeysWithDictionary:dic];
                [self.productArr addObject:search];
                [search release];
            }
            [self.table2 reloadData];
            self.table2.frame = CGRectMake(5, self.text.frame.origin.y + 30,self.view.bounds.size.width - 10, self.view.bounds.size.height - 90);
        }];
    }
    else{
        [self.productArr removeAllObjects];
        self.str = [NSString stringWithFormat:@"http://mrobot.pconline.com.cn/v3/product/select?kw=%@&pageNo=1&pageSize=20", self.text.text];
        [NetHandler getDataWithUrl:self.str completion:^(NSData *data) {
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            NSArray *aa = [result objectForKey:@"resultList"];
            for (NSDictionary *dic in aa) {
                Infor_SearchProduct *search = [[Infor_SearchProduct alloc]init];
                [search setValuesForKeysWithDictionary:dic];
                
                NSString *str = [search.pic stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
                request.HTTPMethod = @"GET";
                [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                    
                    UIImage *image = [UIImage imageWithData:data];
                    search.image = image;
                    [self.table2 reloadData];
                }];
                [self.productArr addObject:search];
                [search release];
            }
            [self.table2 reloadData];
            self.table2.frame = CGRectMake(5, self.text.frame.origin.y + 30,self.view.bounds.size.width - 10, self.view.bounds.size.height - 90);
        }];
    
    }
    [self.text resignFirstResponder];
    
    
}

- (void)clear:(UIButton *)button
{
    NSMutableArray *aa = [NSMutableArray arrayWithArray:self.allArr];
    [aa removeAllObjects];
    self.allArr = [NSArray arrayWithArray:aa];
    NSUserDefaults *uf = [NSUserDefaults standardUserDefaults];
    [uf setObject:self.allArr forKey:@"user1"];

}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.table1.frame = CGRectMake(self.text.frame.origin.x, self.text.frame.origin.y + 30, self.text.bounds.size.width, self.allArr.count * 30);

    return YES;
}

-(void)didChangeComboBoxValue:(AJComboBox *)comboBox selectedIndex:(NSInteger)selectedIndex
{
    if (selectedIndex == 0) {
        [self.productArr removeAllObjects];;
    }else
    {
        [self.productArr removeAllObjects];;
    
    
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.table1) {
        
        return self.allArr.count;
    }
    else{
        return self.productArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.table1) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"a"];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"a"];
        }
        cell.textLabel.text = [self.allArr objectAtIndex:indexPath.row];
        cell.backgroundColor = [UIColor huiseColor];
        return cell;
    }
    else{
        if (self.combox.selectedIndex == 0) {
            InforSearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"b"];
            if (cell == nil) {
                cell = [[InforSearchCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"b"];
            }
            Infor_Search *search = [self.productArr objectAtIndex:indexPath.row];
            cell.title.text = search.title;
            cell.title.numberOfLines = 0;
            cell.title.font = [UIFont systemFontOfSize:15];
            cell.pubDate.text = search.pubDate;
            cell.pubDate.font = [UIFont systemFontOfSize:13];
            return cell;
        }
        else{
            InforProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"c"];
            if (cell == nil) {
                cell = [[InforProductCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"c"];
            }
            Infor_SearchProduct *search = [self.productArr objectAtIndex:indexPath.row];
            cell.title.text = search.title;
            cell.message.text = search.summary;
            NSString *priStr = [NSString stringWithFormat:@"￥:%@",[search.price description]];
            cell.price.text = priStr;
            cell.price.textColor = [UIColor redColor];
            cell.price.font = [UIFont systemFontOfSize:13];
            cell.message.font = [UIFont systemFontOfSize:13];
            cell.imageV.contentMode = UIViewContentModeScaleAspectFit;
            cell.imageV.image = search.image;

            return cell;
        }
    
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.table1) {
        NSString *str = [self.allArr objectAtIndex:indexPath.row];
        self.text.text = str;
        self.table1.frame = CGRectMake(self.text.frame.origin.x, self.text.frame.origin.y + 30, self.text.bounds.size.width, 0);
    }
    else if (tableView == self.table2){
        if (self.combox.selectedIndex == 0) {
            Infor_details_ViewController *details = [[Infor_details_ViewController alloc]init];
            details.search = [self.productArr objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:details animated:YES];
            [details release];
        }
        else{
            Product_Details_ViewController *product = [[Product_Details_ViewController alloc]init];
            product.search = [self.productArr objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:product animated:YES];
            [product release];
            
        
        }
        
        
    }

}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (self.text.text.length != 1) {
        self.table1.frame = CGRectMake(self.text.frame.origin.x, self.text.frame.origin.y + 30, self.text.bounds.size.width, 0);
    }
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.text resignFirstResponder];
    self.table1.frame = CGRectMake(self.text.frame.origin.x, self.text.frame.origin.y + 30, self.text.bounds.size.width, 0);

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
